
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QString>
#include "mbserver.h"
#include "mbclient.h"
#include "datatype.h"

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);

    // 创建服务器和客户端实例
    ModbusServer *server = new ModbusServer(&app);
    ModbusClient *client = new ModbusClient(&app);

    // 创建QML引擎
    QQmlApplicationEngine engine;

    // 注册服务器和客户端到QML上下文
    engine.rootContext()->setContextProperty("modbusServer", server);
    engine.rootContext()->setContextProperty("modbusClient", client);

    // 注册类型到QML系统
    qmlRegisterUncreatableType<ModbusServer>("ModbusDemo", 1, 0, "ModbusServer",
        QString("ModbusServer cannot be created in QML"));
    qmlRegisterUncreatableType<ModbusClient>("ModbusDemo", 1, 0, "ModbusClient",
        QString("ModbusClient cannot be created in QML"));

    // 加载主QML文件
    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                     &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);
    engine.load(url);

    return app.exec();
}
